<script setup>
import { showDialog, showFailToast, showNotify, showSuccessToast } from 'vant'
import { ref } from 'vue'
import logo from '@/assets/images/register-logo.png'
import exclamationMark from '@/assets/images/exclamation-mark.png'
import useUserStore from '@/stores/modules/user'
import { registerJkjl }  from '@/api/jdb'
import { useRouter, useRoute } from 'vue-router'
import { getUserQrCode, getUserQrCodeById } from '@/api/jdb'
import { to as tos } from 'await-to-js'

/**
 * 此页面为下面两种情况公用
 * 1. 分销用户登录后
 * 2. 无需分销用户登录的情况下，学员扫分销用户码跳转进来
 */



const router = useRouter()
const route = useRoute()

const userStore = useUserStore()
const form = ref({
  phone: undefined,
  code: undefined,
})
const sendCodeBtnDisabled = ref(false)
const sendCodeBtnTxt = ref('发送验证码')
const countdownTime = ref(60)
const countdownFlag = ref(0)
const submitLoading = ref(false)
const userId = ref('')

const clearCountdownFlag = () => {
  if (!!countdownFlag.value && countdownFlag.value > 0) {
    clearTimeout(countdownFlag.value)
  }
}
const resetCountdown = () => {
  countdownTime.value = 60
  sendCodeBtnDisabled.value = false
  sendCodeBtnTxt.value = '获取验证码'
  clearCountdownFlag()
}
const countdown = () => {
  if (countdownTime.value <= 0) {
    resetCountdown()
    return
  }
  sendCodeBtnTxt.value = countdownTime.value + '秒后重新获取'
  countdownTime.value--
  sessionStorage.setItem('countdownTime', countdownTime.value)
  setTimeout(countdown, 1000)
}
const startCountdown = () => {
  countdownFlag.value = setTimeout(countdown, 1000)
  sendCodeBtnDisabled.value = true
}
// const sendCode = () => {
//   if(!form.value.phone || form.value.phone.length !== 11) {
//     showFailToast('手机号格式错误')
//     return
//   }
//   startCountdown()
//   // const url = '/jkjl/api/member/getIdentifyingCode?phone=' + form.value.phone +'&scene=register'
//   sendCodeJkjl(form.value.phone).then(response => {
//     console.log(response)
//     if(response.data.msg === '手机号码已存在') {
//       showDialog({
//         title: '消息提示',
//         message: '手机号码已存在，点击确定跳转到下载页',
//       }).then(() => {
//         // window.location.href = '${ctxs}/api/gongzhonghao/register-download?maykey=' + userStore.userId
//       });
//       return
//     }
//     if (response.status === '200') {
//       showSuccessToast('验证码发送成功')
//       return
//     }
//     showFailToast(response.msg)
//   }).catch(error => {
//     showFailToast('网络错误，请稍后重试')
//     console.log(error)
//   })
// }

const onSubmit = async () => {
  if(!form.value.phone || form.value.phone.length !== 11) {
    showFailToast('手机号格式错误')
    return
  }
  // if(!data.form.code || data.form.code.length !== 6) {
  //     vant.Toast.fail('验证码错误')
  //     return
  // }
  submitLoading.value = true

  const registerResponse = await registerJkjl(form.value.phone, userId.value).finally(() => submitLoading.value = false)
  // console.log(registerResponse, 'registerJkjl')
  if (registerResponse.code === 200) {
    // const userQrCodeResponse = await getUserQrCode()
    // if (userQrCodeResponse.data.ynUse === "0") {
    //   //绑定页面
    //   router.push({
    //     path: '/bind-qr-code',
    //     query: {
    //       qrCodeId: userQrCodeResponse.data.id
    //     }
    //   })
    //   return
    // }
    showSuccessToast('绑定成功，即将转到下载页')
    router.push('/share')
    return
  }
  showFailToast({
    message: registerResponse.msg,
    onClose: () => {
      router.push('/share')
    },
  })
}
const init = async () => {
  const countdownTimeFromSessionStorage = sessionStorage.getItem('countdownTime')
  let countdownTimeTotal = 0
  if (!!countdownTimeFromSessionStorage) {
    countdownTimeTotal = parseInt(countdownTimeFromSessionStorage)
  }
  if (!isNaN(countdownTimeTotal) && countdownTimeTotal > 0) {
    countdownTime.value = countdownTimeTotal
    startCountdown()
  }
  if (!!route.query.maykey) {
    //二维码id是从网页url传参进来，优先按传入的二维码id处理
    const [err, userQrCodeResponse] = await tos(getUserQrCodeById({
      maykey: route.query.maykey
    }))
    if (err) {
      router.replace({path: "/error", query: {description: err.message}})
      return
    }

    // console.log(err, 'err')
    // console.log(userQrCodeResponse, 'userQrCodeResponse')

    // const userQrCodeResponse = await getUserQrCodeById({
    //   maykey: route.query.maykey
    // }).catch(error => {
    //   console.log(error, 'userQrCodeResponse')
    // })
    //
    if (userQrCodeResponse.data.ynUse === "0") {
      //如果二维码是空码，进入绑定页面
      router.push({
        path: '/bind-qr-code',
        query: {
          qrCodeId: userQrCodeResponse.data.id,
          redirect: encodeURIComponent(router.currentRoute.value.fullPath || '/')
        }
      })
      return
    }
    userId.value = userQrCodeResponse.data.userId
  } else {
    //如果二维码id不是从网页url传参，需要查询当前登录的用户信息
    if (!userStore.userId) {
      //如果没有用户登录信息，先查询用户登录信息
      const [err] = await tos(useUserStore().getInfo())
      if (err) {
        await useUserStore().logout()
        showNotify({type: "danger", message: err, duration: 5 * 1000})
        router.replace({
          path: '/login'
        })
      }
    }
    userId.value = userStore.userId
  }
}
init()
</script>

<template>
  <div class="app-container">
    <header>
      <van-image :src="logo" style="width:30px;height:30px;" round></van-image>
      <div style="font-size: 25px;color:#08121F;margin-left:5px;">
        驾多宝
      </div>
    </header>
    <section style="font-size: 32px;color:#0D5DC7;width:330px;margin:8px auto 0;text-align: center;">获取本地专属考试题库</section>

    <!--        <section style="width:310.5px;margin:40px auto 0;font-size:16px;">手机号码</section>-->
    <van-form @submit="onSubmit" class="form">
      <van-cell-group inset class="form-cell-group">
        <van-field
            error-message-align="center"
            style="background: none;"
            center
            input-align="center"
            v-model="form.phone"
            name="手机号"
            placeholder="请输入手机号码"
        >
          <template #label>
            <div style="width: 100%;text-align: right;color:#32434C;font-size:16px;font-weight: 500">手机号：</div>
            <!--                        <div style="display: flex">-->
            <!--                            <div style="margin-right:15px;">手机号:</div>-->
            <!--                            <div style="font-size: 12px;font-weight: bold;color:#C3C5C9">|</div>-->
            <!--                        </div>-->
          </template>
        </van-field>
      </van-cell-group>
      <!--            <div class="form-border"></div>-->
      <!--        <van-cell-group inset class="form-cell-group">-->
      <!--            <van-field-->
      <!--                    maxlength="6"-->
      <!--                    error-message-align="center"-->
      <!--                    center-->
      <!--                    input-align="center"-->
      <!--                    style="background: none;"-->
      <!--                    v-model="form.code"-->
      <!--                    name="验证码"-->
      <!--                    placeholder="请填写验证码"-->
      <!--            >-->
      <!--                <template #button>-->
        <!--                    <van-button-->
        <!--                            :disabled="sendCodeBtnDisabled"-->
        <!--                            type="primary"-->
        <!--                            round-->
        <!--                            @click.stop.prevent="sendCode"-->
        <!--                            size="mini"-->
        <!--                            color="#0296F6"-->
        <!--                            style="padding:0 20px;"-->
        <!--                    >-->
        <!--                        {{sendCodeBtnTxt}}-->
        <!--                    </van-button>-->
        <!--                </template>-->
      <!--            </van-field>-->
      <!--        </van-cell-group>-->
      <!--        <div style="margin: 16px;">-->
      <van-button
          style="width:311px;height:60px;margin:51px auto 0;font-size:18px;font-weight:bold;border-radius: 60px"
          block
          type="primary"
          native-type="submit"
          color="#2B83F7"
          :loading="submitLoading"
          loading-text="加载中..."
      >
        下一步
      </van-button>
      <!--        </div>-->
    </van-form>
    <div class="exclamation-mark">
      <van-image :src="exclamationMark" style="width:15px;height:15px;"></van-image>
      <div style="font-size:14px;font-weight:bold;color:#DE2335;text-align:center;margin-left:5px;">下载驾多宝后一定要用以上输入的手机号登录</div>
    </div>

    <div style="margin:142px auto 0;font-size:25px;color:#2B83F7;width: 100%;text-align: center">
      <div>驾考软件广告做的好</div>
      <div style="margin-top:6px;">不如驾多宝题库好</div>
    </div>
    <!--        <div class="footer-banner">-->
    <!--            <img src="${ctxStatic}/html/img/register-background.png?v=<%=currentTimeMillisWillTransferToStr%>">-->
    <!--        </div>-->
  </div>
  <!--    <van-nav-bar title="学员注册"></van-nav-bar>-->

  <!--    <header class="header-title">-->
  <!--        ${schoolName}-->
  <!--    </header>-->
  <!--    <section class="section-title">-->
  <!--        教练姓名：<span style="color: #0089E1;">${coachName}</span>-->
  <!--    </section>-->
  <!--    <section class="section-content">-->
  <!--        获取本地专属题库-->
  <!--    </section>-->

  <!--    <footer> 驾考广告做的好，不如驾多宝题库好 </footer>-->
</template>

<style scoped>
.app-container {
  min-height: 100vh;
  background: #DAF2FE;
}
:deep(.van-field__control::-webkit-input-placeholder) {
  color: #8B9CA5 !important;
}
:deep(.van-field__control::placeholder) {
  color: #8B9CA5 !important;
}
/*.form-cell-group{*/
/*    overflow: hidden;*/
/*    margin-top:20px;*/
/*    margin-bottom:20px;*/
/*    background:#EDEDED;*/
/*    border-radius: var(--van-button-round-border-radius);*/
/*}*/
.form {
  overflow: hidden;margin:58px auto 0;width:343px;text-align: center;
}
.logo {
  width:56px;height:56px;display: block;margin:50px auto 20px;overflow: hidden;
}
.header-title {
  font-size: 24px;font-weight: bold;text-align: center;margin-bottom: 10px;
}
.section-title {
  font-size:18px;font-weight: bold;text-align: center;margin-bottom:10px;
}
.section-content {
  font-size:18px;font-weight: bold;text-align: center;margin:50px 0 30px;letter-spacing: 10px;text-indent:10px;
}

footer{
  font-size:16px;text-align: center;margin:0 auto;
}


header {
  padding-top:25px;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: center;
  width:310px;
  margin:0 auto;
  justify-content: center;
}
.exclamation-mark {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: center;
  width:100%;
  margin:16px auto 0;
  justify-content: center;
}
.form-cell-group :deep(.van-field__control) {
  font-size:18px;
  text-align:left;
}
.form-cell-group :deep(.van-field__label) {
  font-size:16px;
  color: #32434C;
  width:100px;
  margin: 0;
}
.form-cell-group :deep(.van-cell) {
  /*padding-bottom:5px !important;*/
  padding-left: 0;
  padding-right: 0;
  width: 311px;
  margin: 0 auto;
  height:60px;
}
.form-border {
  width:311px;
  height:2px;
  margin:0 auto;
  background-color:#F6F6F8;
  /*border-bottom:2px solid #F6F6F8;*/
}

.footer-banner {
  padding: 15.15% 0 0;
  position: relative;
}
.footer-banner > img {
  position: absolute;
  width: 100%;
  min-height: 321.5px;
  left: 0; top: 0;
  /*background:#fff;*/
}
.app-container {
  /*background:#fff;*/
}
.van-cell-group--inset {
  border-radius: 60px;
}
</style>
